package com.huatai.common.util;

import java.io.*;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @program: nanming-saas
 * @description: 压缩文件
 * @author: songxiude
 * @create: 2024-06-21 14:04
 **/

public class FileZipper {

	public static boolean zipFiles(List<File> fileList, String zipFilePath) {
		try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFilePath))) {
			for (File file : fileList) {
				if (file.exists()) {
					compress(file, zos, file.getName(), true);
				}
			}
			return true;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
	}

	private static void compress(File sourceFile, ZipOutputStream zos, String name, boolean KeepDirStructure)
		throws IOException {
		byte[] buffer = new byte[4096];
		if (sourceFile.isFile()) {
			try (FileInputStream fis = new FileInputStream(sourceFile)) {
				ZipEntry zipEntry;
				if (KeepDirStructure) {
					zipEntry = new ZipEntry(name);
				} else {
					zipEntry = new ZipEntry(sourceFile.getName());
				}
				zos.putNextEntry(zipEntry);
				int length;
				while ((length = fis.read(buffer)) > 0) {
					zos.write(buffer, 0, length);
				}
				zos.closeEntry();
			}
		} else if (sourceFile.isDirectory()) {
			File[] files = sourceFile.listFiles();
			if (files != null) {
				for (File file : files) {
					if (KeepDirStructure) {
						compress(file, zos, name + File.separator + file.getName(), KeepDirStructure);
					} else {
						compress(file, zos, file.getName(), KeepDirStructure);
					}
				}
			}
		}
	}
}

